package com.ruoyi.common.utils.sms;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import com.google.gson.Gson;
import com.ruoyi.common.constant.SmsConstants;
import darabonba.core.client.ClientOverrideConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author Administrator
 * @description 短信服务
 * @data 2023/2/22 9:31
 */
public class SendSmsUtil {

    private static Logger logger = LoggerFactory.getLogger(SendSmsUtil.class);
    public static void main(String[] args) {
       sendInfo("15138478643","{\"time\":\"2025-05-20 22:22:09\",\"number\":\"022025040001\",\"address\":\"1号管网哨兵\",\"value\":\"2\"}");
//        sendInfo("15138478643","{\"code\":\"2346\"}");
    }
    /**
     *
     * @param phone 手机号
     * @param json  参数
     */
    public static Response sendInfo(String phone, String json){
        logger.error("参数：手机号 {}，json串 {}",phone,json);
        return sendInfo(SmsConstants.ACCESSKEY_ID,SmsConstants.ACCESSKEY_SECRET,SmsConstants.SIGN_NAME,SmsConstants.TEMPLATE_CODE1,phone,json);
    }

    // 根据不同的模板 发送不同的信息
    public static Response sendInfoByTemplate(String phone, String json, String template){
        return sendInfo(SmsConstants.ACCESSKEY_ID,SmsConstants.ACCESSKEY_SECRET,SmsConstants.SIGN_NAME,template,phone,json);
    }
    public static Response sendInfo(String accesskeyId, String accessKeySecret, String signName, String templateCode, String phoneNumber, String json){
        Response rp = Response.ok();
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accesskeyId)
                .accessKeySecret(accessKeySecret)
                //.securityToken("<your-token>") // use STS token
                .build());
        AsyncClient client = AsyncClient.builder()
                .region("cn-qingdao") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        /*SendBatchSmsRequest sendBatchSmsRequest = SendBatchSmsRequest.builder()
                .signNameJson("")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

*/
        //13693712046 15138478643
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName)
                .templateCode(templateCode)
                .phoneNumbers(phoneNumber)
                .templateParam(json)
//                .templateParam("{\"code\":\"2346\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        try {
            SendSmsResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            if(resp.getStatusCode()==200){
                SendSmsResponseBody body = resp.getBody();
                String code = body.getCode();
                if("OK".equals(code)){
                    rp = new Response(200,body.getMessage(),null);
                }else{
                    rp = new Response(500,body.getMessage(),null);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        // Finally, close the client
        client.close();
        return rp;
    }
}
